<template>
  <a-modal
    :visible="visible"
    :title="title"
    :width="676"
    :footer="!disabled"
    :unmount-on-close="true"
    :ok-loading="loading"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <a-form ref="memberRef" :model="formData" :disabled="disabled">
      <a-row :gutter="16">
        <a-col flex="320px">
          <a-form-item
            field="username"
            label="用户名"
            validate-trigger="input"
            :disabled="disabled || title == '编辑成员'"
            :rules="[
              {
                required: true,
                message: '用户名必填',
              },
            ]"
            label-col-flex="68px"
          >
            <UserSelector
              v-model="formData.username"
              placeholder="请选择/输入"
              allow-create
              :using-name="true"
              show-user-name
              @change="getUserInfo"
            />
          </a-form-item>
        </a-col>
        <a-col flex="320px">
          <a-form-item
            field="name"
            label="姓名"
            label-col-flex="68px"
            validate-trigger="input"
            :rules="[
              {
                required: true,
                message: '姓名必填',
              },
            ]"
          >
            <a-input v-model="formData.name" placeholder="请输入姓名" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col flex="320px">
          <a-form-item
            field="phone"
            label="手机"
            label-col-flex="68px"
            validate-trigger="input"
            :rules="[
              {
                required: true,
                message: '手机必填',
              },
              {
                match: /^1[3456789]\d{9}$/,
                message: $t('login.form.telInvalid'),
              },
            ]"
          >
            <a-input v-model="formData.phone" placeholder="请输入手机" />
          </a-form-item>
        </a-col>
        <a-col flex="320px">
          <a-form-item
            field="email"
            label="邮箱"
            validate-trigger="input"
            :rules="[
              {
                required: true,
                message: '邮箱必填',
              },
              {
                match: /^[A-Za-z0-9_]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g,
                message: $t('userSetting.form.email.error'),
              },
            ]"
            label-col-flex="68px"
          >
            <a-input v-model="formData.email" placeholder="请输入邮箱" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col flex="320px">
          <a-form-item field="role" label="角色" label-col-flex="68px">
            <a-input v-model="formData.role" placeholder="请输入角色" />
          </a-form-item>
        </a-col>
        <a-col flex="320px">
          <a-form-item
            field="projectAdmin"
            label="成员类型"
            :rules="[
              {
                required: true,
                message: '成员类型必填',
              },
            ]"
            label-col-flex="68px"
          >
            <a-select
              v-model="formData.projectAdmin"
              placeholder="请选择成员类型"
            >
              <a-option :value="0">普通成员</a-option>
              <a-option :value="1">项目管理员</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col flex="320px">
          <a-form-item
            field="moduleVisible"
            label="可见模块"
            :rules="[
              {
                required: true,
                message: '科技模块必填',
              },
            ]"
            label-col-flex="68px"
          >
            <a-checkbox-group v-model="formData.moduleVisible">
              <a-checkbox value="0">文件</a-checkbox>
              <a-checkbox value="1">协同平台</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import { MemberRecord, addMember, updateMember } from '@/api/member';
  import { isArray } from '@/utils/is';
  import useLoading from '@/hooks/loading';
  import UserSelector from '@/components/user-selector/index.vue';

  interface MemberRecordExt extends Partial<MemberRecord> {
    moduleVisible?: string[];
  }
  const { loading, setLoading } = useLoading(false);

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: true,
    },
    form: {
      type: Object,
      default() {
        return {
          name: '',
          email: '',
          phone: '',
          role: '',
          projectAdmin: 0,
          moduleVisible: '0,1',
        };
      },
    },
  });
  const emit = defineEmits(['update:visible', 'refresh']);

  const formatForm = (form: MemberRecord): MemberRecordExt => {
    const { moduleVisible, ...rest } = form;
    let moduleVisibleArray: string[] = [];
    if (!isArray(moduleVisible)) {
      moduleVisibleArray = moduleVisible?.split(',') || [];
    }
    return {
      ...rest,
      moduleVisible: moduleVisibleArray,
    };
  };
  const formData = ref<MemberRecordExt>(formatForm(props.form));
  watch(
    () => props.form,
    (n) => {
      formData.value = formatForm(n);
    }
  );

  const memberRef = ref<FormInstance>();
  const handleBeforeOk = async (done: any) => {
    const res = await memberRef.value?.validate();
    if (!res) {
      setLoading(true);
      let flg = false;
      let msg = '添加成功';
      if (props.title === '编辑成员') {
        flg = await editMember();
        msg = '修改成功';
      } else if (props.title === '添加成员') {
        flg = await addOneMember();
      } else {
        // 查看无按钮
      }
      if (flg) {
        Message.success(msg);
        emit('update:visible', false);
        emit('refresh');
      }
      setLoading(false);
      done();
    }
  };
  const editMember = async () => {
    try {
      const { moduleVisible, id, ...rest } = formData.value;
      const moduleVisibleString = moduleVisible?.join(',') || '';
      const res = await updateMember({
        ...rest,
        userId: id,
        moduleVisible: moduleVisibleString,
      });
      return !!res.status;
    } catch (error) {
      return false;
    }
  };
  // TODO: 未实现添加已有成员逻辑
  const addOneMember = async () => {
    try {
      const { moduleVisible, ...rest } = formData.value;
      const moduleVisibleString = moduleVisible?.join(',') || '';
      const res = await addMember({
        ...rest,
        moduleVisible: moduleVisibleString,
      });
      return !!res.status;
    } catch (error) {
      return false;
    }
  };
  const handleCancel = () => {
    emit('update:visible', false);
  };
  const getUserInfo = (val: any) => {
    // 此处有值表示选择，undefined表示新加或数据为空
    if (val) {
      // 赋值姓名，手机和邮箱
      formData.value.name = val.name;
      formData.value.email = val.email;
      formData.value.phone = val.phone;
    }
    // else {
    //   formData.value.name = '';
    //   formData.value.email = '';
    //   formData.value.phone = '';
    // }
  };
</script>

<script lang="ts">
  export default {
    name: 'AddMember',
  };
</script>
